import {Injectable} from '@angular/core';

/**  缓存服务 */
@Injectable()
export class CacheService {
  constructor() {

  }

  private usercache: { [key: string]: string };

  get UserCache() {
    if (!this.usercache) {
      const usercachestr = localStorage.getItem('usercache');
      if (usercachestr) {
        this.usercache = JSON.parse(usercachestr.de());
      } else {
        this.usercache = {};
      }
    }
    return this.usercache;
  }

  private lusername: string;

  get LastUserName() {
    if (!this.lusername) {
      this.lusername = localStorage.getItem('lusername');
      if (this.lusername) {
        this.lusername = this.lusername.de();
      }
    }
    return this.lusername;
  }

  set LastUserName(value) {
    localStorage.setItem('lusername', value.en());
    this.lusername = value;
  }

  SetUser(user: { userName: string, password: string }, isPersistent: boolean) {
    if (isPersistent) {
      this.UserCache[user.userName] = user.password;
      this.LastUserName = user.userName;
    } else {
      if (this.UserCache[user.userName]) {
        delete this.UserCache[user.userName];
      } else {
        const keys = Object.keys(this.UserCache);
        if (keys.length) {
          this.LastUserName = keys[0];
        }
        return;
      }
    }
    localStorage.setItem('usercache', JSON.stringify(this.UserCache).en());
  }
}
